package moe.server;

import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import moe.collection.PreviewCreater;
import moe.config.Configuration;
import moe.dao.BaseDao;
import moe.dao.CollectionDao;
import moe.dao.PostDao;
import moe.entity.Collection;
import moe.entity.Post;
import moe.util.UriMappedUtil;

public class CollectionStaticResourcesHandler extends StaticResourcesHandler {
	private final static Pattern idPattern = Pattern.compile("^.+[/\\\\]moe (\\d+)[ .].+$");
	private final static String PREVIEW_DIR = System.getProperty("user.dir") + File.separator
			+ "preview" + File.separator;

	private CollectionDao collectionDao = new CollectionDao();
	private PostDao postDao = new PostDao(BaseDao.ConnType.COLLECTION);

	@Override
	protected String resolveFilePath(String uri) {
		String path = null;
		if (uri.startsWith("/collection/preview")) {
			path = PREVIEW_DIR
					+ UriMappedUtil
							.escapeIllegalSystemChar(uri.replace("/collection/preview/", ""));
		} else if (uri.startsWith("/collection/convert")) {
			if (Configuration.isCreateThumbnails()) {
				path = createPreview(uri);
			}
		} else if (uri.startsWith("/collection")) {
			path = getPath(getId(uri));
		} else {
			path = super.resolveFilePath(uri);
		}
		return path;
	}

	private String createPreview(String uri) {
		Post post = getPost(getId(uri));
		if (post == null) {
			return null;
		}
		return doCreatePreview(post);
	}

	private String doCreatePreview(Post post) {
		Collection collection = collectionDao.getCollection(post.id);
		if (collection == null) {
			return null;
		}
		int width = post.width, height = post.height;
		if (width > height) {
			height = height * 300 / width;
			width = 300;
		} else {
			width = width * 300 / height;
			height = 300;
		}
		StringBuilder pathBuilder = new StringBuilder();
		pathBuilder.append(PREVIEW_DIR)
				.append("thumbnail.")
				.append(collection.getName());
		String outFilepath = pathBuilder.toString();
		new File(PREVIEW_DIR).mkdirs();
		try {
			PreviewCreater.createPreview(collection.getFilePath(), outFilepath, width,
					height);
		} catch (Throwable e) {
			log.warning("Thumbnail create failed, file:" + collection.getFilePath());
		}
		return outFilepath;
	}

	private long getId(String uri) {
		Matcher matcher = idPattern.matcher(uri);
		if (matcher.matches()) {
			return Long.valueOf(matcher.group(1));
		} else {
			throw new RuntimeException("Illegal URI:" + uri);
		}
	}

	private String getPath(long id) {
		Collection collection = collectionDao.getCollection(id);
		if (collection == null) {
			return null;
		}
		return collection.getFilePath();
	}

	private Post getPost(long id) {
		return postDao.getPost(id);
	}
}
